#!/usr/bin/env bash

TOPLEVEL=$(dirname "$0")

bali_apply_target() {
    echo "apply target $1"
    NEWNAME=$(basename "$1")
    DIRNAME=$(dirname "$1")
    NAME="${NEWNAME/%.new/}"
    TARGETFILE="$DIRNAME/$NAME"
    if [[ ! -d "$DIRNAME/old" ]]; then
        mkdir -p "$DIRNAME/old"
    fi
    if [[ -f "$DIRNAME/old/$NAME.3" ]]; then
        rm "$DIRNAME/old/$NAME.3"
    fi
    if [[ -f "$DIRNAME/old/$NAME.2" ]]; then
        mv "$DIRNAME/old/$NAME.2" "$DIRNAME/old/$NAME.3"
    fi
    if [[ -f "$DIRNAME/old/$NAME.1" ]]; then
        mv "$DIRNAME/old/$NAME.1" "$DIRNAME/old/$NAME.2"
    fi

    if [[ -f "$DIRNAME/$NAME.old" ]]; then
        mv "$DIRNAME/$NAME.old" "$DIRNAME/old/$NAME.1"
    fi
    ###
    if [[ -f "$TARGETFILE" ]]; then
        mv "$TARGETFILE" "$TARGETFILE.old"
    fi
    mv "$TARGETFILE.new" "$TARGETFILE"
}

bali_apply_config() {
    NEWNAME=$(basename "$1")
    DIRNAME=$(dirname "$1")
    NAME="${NEWNAME/%.template/}"
    echo -e "install config \x1b[33m$1\x1b[0m"
    if [[ ! -d "$DIRNAME" ]]; then
        mkdir -p "$DIRNAME"
    fi
    if [[ -f "$DIRNAME/$NAME" ]]; then
        echo "File $NAME exists in $DIRNAME"
        git --no-pager diff --no-index "$1" "$DIRNAME/$NAME"
        rm "$1"
    else
        echo "rename $1 to $DIRNAME/$NAME"
        mv "$1" "$DIRNAME/$NAME"
    fi
}

#------------------
rm "$TOPLEVEL/post_install.sh"
